﻿# 配置版本号和OSS目录
$customVersion = "master" # 配置版本号
$ossDirectory = "oss://public-chengdu" # 配置OSS目录 oss://your-bucket/directory

# 设置版本
$version = if ($customVersion) { $customVersion } else { Read-Host "Please input version (default:latest)" }
if ([string]::IsNullOrEmpty($version)) {
    $version = "latest"
}

if (-not $ossDirectory) {
    $ossDirectory = Read-Host "Please input OSS directory"
}

# 获取项目文件
$projectFile = Get-ChildItem -Path $PSScriptRoot -Filter *.csproj | Select-Object -First 1
if (-not $projectFile) {
    Write-Error "未找到 .csproj 文件，请确保脚本位于项目根目录下。"
    Read-Host -Prompt "按 Enter 键继续..."
    exit 1
}

# 尝试从 .csproj 文件中提取 AssemblyName
[xml]$projectXml = Get-Content $projectFile.FullName
$assemblyNameNode = $projectXml.Project.PropertyGroup.AssemblyName

if ($assemblyNameNode) {
    $projectName = $assemblyNameNode
} else {
    # 如果无法提取 AssemblyName，则使用项目文件名（去掉扩展名）
    $projectName = [System.IO.Path]::GetFileNameWithoutExtension($projectFile.Name)
}

Write-Host "Detected Project Name: $projectName"

# 定义变量
$outputPath = Join-Path $PSScriptRoot "bin\publish"
$zipFileName = "$($projectName).$version.zip"
$zipFile = Join-Path $PSScriptRoot "bin\$zipFileName"

# 清理先前的发布输出
if (Test-Path $outputPath) {
    Remove-Item -Recurse -Force $outputPath
}

# 发布项目
Write-Host "Publishing project..."
dotnet publish -c Release -o $outputPath
if ($LASTEXITCODE -ne 0) {
    Write-Host "Error during project publish."
    exit $LASTEXITCODE
} else {
    Write-Host "Project published successfully."
}

# 压缩 bin 目录下的 publish 文件夹到 zip 文件
Write-Host "Compressing publish directory to ZIP file..."
Compress-Archive -Path "$outputPath\*" -DestinationPath $zipFile -Force
if ($LASTEXITCODE -ne 0) {
    Write-Host "Error during compression."
    exit $LASTEXITCODE
} else {
    Write-Host "Compression completed successfully."
}

# 上传到OSS
Write-Host "Uploading ZIP file to OSS..."
& ossutil cp $zipFile "$ossDirectory/$zipFileName" -f
if ($LASTEXITCODE -ne 0) {
    Write-Host "Error during OSS upload."
    exit $LASTEXITCODE
} else {
    Write-Host "OSS upload completed successfully."
}

Write-Output "发布完成！压缩包路径: $zipFile"

Read-Host -Prompt "按 Enter 键继续..."



